/**
 * 
 */
package com.parktech.sun.utils.action;

//import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @title http请求相关方法
 * @author defier Lai
 * Aug 22, 2009 5:43:44 PM
 *
 */
public class HttpRequestProxy {

//	private final static Logger LOG = Logger.getLogger(HttpRequestProxy.class);
	/**
	 * 连接超时
	 */
	private static int connectTimeOut = 5000;
	/**
	 * 读取数据超时
	 */
	private static int readTimeOut = 10000;

	public static String encode(String target, String requestEncoding) {
		String result = (target != null) ? target.toString() : "";
		try {
			result = URLEncoder.encode(result, requestEncoding);
		} catch (UnsupportedEncodingException e) {
//			LOG.error("Unsuccessful attempt to encode '" + result + "' into UTF8");
		}
		return result;
	}

	public static BDom4j postRequest(Map<String, String> parameters, 
						String reqUrl, String recvEncoding, String requestEncoding) throws IOException {
		HttpURLConnection url_con = null;
		try {
			StringBuffer params = new StringBuffer();
			for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
				Entry<String, String> element = (Entry<String, String>) iter.next();
				params.append(element.getKey().toString());
				params.append("=");
				params.append(encode(String.valueOf(element.getValue()), requestEncoding));
				params.append("&");
			}
			System.out.println(params);
			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}

			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
//			System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connectTimeOut));// （单位：毫秒）jdk1.4换成这个,连接超时
//			System.setProperty("sun.net.client.defaultReadTimeout", String
//					.valueOf(HttpRequestProxy.readTimeOut)); // （单位：毫秒）jdk1.4换成这个,读操作超时
			 url_con.setConnectTimeout(connectTimeOut);//（单位：毫秒）jdk
			url_con.setReadTimeout(readTimeOut);//（单位：毫秒）jdk 1.5换成这个,读操作超时
			url_con.setDoOutput(true);
			url_con.connect();
			byte[] b = params.toString().getBytes();
			url_con.getOutputStream().write(b, 0, b.length);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
//			LOG.info("请求URL："+reqUrl);
			BDom4j dom = new BDom4j();
			dom.openXML(url_con.getInputStream());
			return dom;
			
		} catch (IOException e) {
//			LOG.error("网络故障", e);
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
		return null;
	}

	
	public static String postHttpRequest(Map<String, String> parameters, String reqUrl, String recvEncoding, String requestEncoding) throws IOException {
		HttpURLConnection url_con = null;
		try {
			StringBuffer params = new StringBuffer();
			for (Iterator<Entry<String, String>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
				Entry<String, String> element = (Entry<String, String>) iter.next();
				params.append(element.getKey().toString());
				params.append("=");
				params.append(encode(element.getValue().toString(), requestEncoding));
				params.append("&");
			}

			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}

			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
//			System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connectTimeOut));// （单位：毫秒）jdk1.4换成这个,连接超时
//			System.setProperty("sun.net.client.defaultReadTimeout", String
//					.valueOf(HttpRequestProxy.readTimeOut)); // （单位：毫秒）jdk1.4换成这个,读操作超时
			 url_con.setConnectTimeout(connectTimeOut);//（单位：毫秒）jdk
			url_con.setReadTimeout(readTimeOut);//（单位：毫秒）jdk 1.5换成这个,读操作超时
			url_con.setDoOutput(true);
			url_con.connect();
			byte[] b = params.toString().getBytes();
			url_con.getOutputStream().write(b, 0, b.length);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
//			LOG.info("请求URL："+reqUrl);
			return processInputStream(recvEncoding, url_con.getInputStream());
			
		} catch (IOException e) {
//			LOG.error("网络故障", e);
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
		return null;
	}
	
	public static String processInputStream(String recvEncoding, InputStream in) throws UnsupportedEncodingException, IOException {
		String responseContent;
		BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding));
		String tempLine = rd.readLine();
		StringBuffer tempStr = new StringBuffer();
		String crlf = System.getProperty("line.separator");
		while (tempLine != null) {
			tempStr.append(tempLine);
			tempStr.append(crlf);
			tempLine = rd.readLine();
		}
		responseContent = tempStr.toString();
		rd.close();
		return responseContent;
	}
	
	
}
